# Copyright IBM, Corp. 2012
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
# Refer to the README and COPYING files for full details of the license
#


import subprocess

from vdsm.tool import expose


EX_MODPROBE = '/usr/sbin/modprobe'


def _exec_command(argv):
    """
    This function executes a given shell command.
    """

    p = subprocess.Popen(argv, stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
    out, err = p.communicate()
    rc = p.returncode
    if rc != 0:
        raise Exception("Execute command %s failed: %s" % (argv, err))


def _enable_bond_dev():
    REQUIRED = set(['bond0', 'bond1', 'bond2', 'bond3', 'bond4'])
    MASTER_FILE = '/sys/class/net/bonding_masters'

    # oVirt Engine currently assumes that all bonding devices pre-exist
    existing = set(file(MASTER_FILE).read().split())
    with open(MASTER_FILE, 'w') as f:
        for bond in REQUIRED - existing:
            f.write('+%s\n' % bond)


@expose('load-needed-modules')
def load_needed_modules():
    """
    Load needed modules
    """

    for mod in ['tun', 'bonding', '8021q']:
        _exec_command([EX_MODPROBE, mod])
    _enable_bond_dev()
